package com.echo.distributedlock.service.impl;

import com.echo.distributedlock.api.DbLock;
import com.echo.distributedlock.service.LockService;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * @author lmy
 */
@Service
public class DbLockServiceImpl implements LockService {

    @Resource
    private ApplicationContext applicationContext;

    private DataSource dataSource;

    @PostConstruct
    public void init() {
        dataSource = applicationContext.getBean(DataSource.class);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String isTableSql = "SELECT COUNT(*) as count FROM information_schema.TABLES WHERE table_name = 'ECHO_LOCK' AND table_schema = (select database())";
        Map<String, Object> map = jdbcTemplate.queryForMap(isTableSql);
        if (Integer.parseInt(map.get("count").toString()) == 0) {
            String createSql = "CREATE TABLE `ECHO_LOCK` (" +
                    "  `key` varchar(255) NOT NULL," +
                    "  PRIMARY KEY (`key`)" +
                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
            jdbcTemplate.execute(createSql);
        }
    }


    @Override
    public Lock getLock(String key) {
        return new DbLock(key, dataSource);
    }
}
